import axios from 'axios'
import { message as Message } from 'ant-design-vue'
import store from '@/store'
import { get } from 'lodash-es'
import { getToken, isLogin } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    icode: 'helloqianduanxunlianying'
  }
})

service.interceptors.request.use(
  (config) => {
    if (isLogin()) config.headers.Authorization = `Bearer ${getToken()}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  (response) => {
    if (response?.data) {
      const { message, success } = response.data
      // 全局错误提示 - 如果 success 为 false 则提示错误信息
      !success && Message.error(message)
    }
    return get(response, 'data', {})
  },
  (error) => {
    if (error?.response?.data) {
      if (error?.response?.data.code === 401) {
        store.dispatch('user/logout')
      }
    }
    Message.error(error?.response?.data?.message || '请求异常')
    return Promise.reject(error)
  }
)
export default service
